<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="领料单号">
              <a-input placeholder="请输入领料单号" v-model="queryParam.requisitionNo_like"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单编号">
              <a-input placeholder="请输入订单编号" v-model="queryParam.orderNo_like"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="审核状态">
              <j-dict-select-tag
                placeholder="请选择审核状态"
                v-model="queryParam.status"
                dictCode="requisition_status"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="审核人">
              <j-select-employee-modal
                v-model="queryParam.approver"
                :departName="'生产部'"
                :multiple="false"
                @change="handleApproverChange"
              ></j-select-employee-modal>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="审核日期">
              <a-range-picker
                :placeholder="['开始日期', '结束日期']"
                format="YYYY-MM-DD"
                v-model="queryParam.approveTime"
                @change="handleApproveTimeChange"
                :getCalendarContainer="getCalendarContainer"
                :key="'approveTime' + datePickerKey"
                allowClear
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="领料日期">
              <a-range-picker
                :placeholder="['开始日期', '结束日期']"
                format="YYYY-MM-DD"
                v-model="queryParam.requisitionDate"
                @change="handleRequisitionDateChange"
                :getCalendarContainer="getCalendarContainer"
                :key="'requisitionDate' + datePickerKey"
                allowClear
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="领料状态">
              <j-dict-select-tag
                placeholder="请选择领料状态"
                v-model="queryParam.pickingStatus"
                dictCode="requisition_picking_status"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button type="primary" icon="plus" @click="handleAdd" v-if="hasPermission('wms:requisition:add')">新增</a-button> -->
      <a-button type="primary" icon="download" @click="handleExport" v-if="hasPermission('wms:requisition:export')"
        >导出</a-button
      >
      <!-- <a-button type="primary" icon="printer" @click="handleBatchPrint" v-if="hasPermission('wms:requisition:print')">批量打印领料单</a-button> -->
      <a-dropdown v-if="selectedRowKeys.length > 0 && hasPermission('wms:requisition:delete')">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"> <a-icon type="delete" />删除 </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div class="table-wrapper">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1500, y: 500 }"
        class="requisition-table"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <!-- 查看按钮：所有状态都可查看 -->
          <a @click="handleView(record)" v-if="hasPermission('wms:requisition:query')">查看</a>

          <!-- 待审核状态(0)：编辑、通过、驳回、打印、删除 -->
          <template v-if="record.status == 0">
            <a-divider type="vertical" v-if="hasPermission('wms:requisition:edit')" />
            <a @click="handleEdit(record)" v-if="hasPermission('wms:requisition:edit')">编辑</a>

            <a-divider type="vertical" v-if="hasPermission('wms:requisition:approve')" />
            <a @click="handleApprove(record)" v-if="hasPermission('wms:requisition:approve')">通过</a>

            <a-divider type="vertical" v-if="hasPermission('wms:requisition:reject')" />
            <a @click="handleReject(record)" v-if="hasPermission('wms:requisition:reject')">驳回</a>

            <a-divider type="vertical" v-if="hasPermission('wms:requisition:delete')" />
            <a-popconfirm
              title="确定删除吗?"
              @confirm="() => handleDelete(record.id)"
              v-if="hasPermission('wms:requisition:delete')"
            >
              <a>删除</a>
            </a-popconfirm>
          </template>

          <!-- 已审核状态(1)：审核信息 -->
          <template v-if="record.status == 1">
            <a-divider type="vertical" />
            <a @click="handleViewApproveInfo(record)">审核信息</a>
          </template>

          <!-- 所有状态都可打印 -->
          <a-divider type="vertical" v-if="hasPermission('wms:requisition:print')" />
          <a @click="handlePrint(record)" v-if="hasPermission('wms:requisition:print')">打印</a>
        </span>

        <template slot="statusSlot" slot-scope="text, record">
          <a-tag :color="text == '0' ? 'orange' : text == '1' ? 'green' : 'red'">
            {{ record.status_dictText || '未知状态' }}
          </a-tag>
        </template>

        <template slot="optimizationSoftwareTypeSlot" slot-scope="text">
          <a-tag :color="text == '0' ? 'blue' : 'purple'">
            {{ text == '0' ? '长风' : '新格尔' }}
          </a-tag>
        </template>

        <template slot="pickingStatusSlot" slot-scope="text">
          <a-tag :color="text == '0' ? 'orange' : text == '1' ? 'blue' : 'green'">
            {{ text == '0' ? '未领料' : text == '1' ? '部分领料' : '全部领料' }}
          </a-tag>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <requisition-modal ref="modalForm" @ok="modalFormOk"></requisition-modal>
    <requisition-view-modal ref="viewModal"></requisition-view-modal>
    <requisition-approve-modal ref="approveModal" @ok="modalFormOk"></requisition-approve-modal>
    <requisition-reject-modal ref="rejectModal" @ok="modalFormOk"></requisition-reject-modal>
    <requisition-print-modal ref="printModal"></requisition-print-modal>
    <requisition-approve-info-modal ref="approveInfoModal"></requisition-approve-info-modal>
  </a-card>
</template>

<script>
import RequisitionModal from './modules/RequisitionModal'
import RequisitionViewModal from './modules/RequisitionViewModal'
import RequisitionApproveModal from './modules/RequisitionApproveModal'
import RequisitionRejectModal from './modules/RequisitionRejectModal'
import RequisitionPrintModal from './modules/RequisitionPrintModal'
import RequisitionApproveInfoModal from './modules/RequisitionApproveInfoModal'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import JDictLabel from '@/components/dict/JDictLabel.vue'
import JDate from '@/components/jeecg/JDate.vue'
import JSelectEmployeeModal from '@/components/jeecgbiz/JSelectEmployeeModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, postAction, deleteAction } from '@/api/manage'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'
import Vue from 'vue'
import { downFile } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'RequisitionList',
  mixins: [JeecgListMixin],
  components: {
    RequisitionModal,
    RequisitionViewModal,
    RequisitionApproveModal,
    RequisitionRejectModal,
    RequisitionPrintModal,
    RequisitionApproveInfoModal,
    JDictSelectTag,
    JDictLabel,
    JDate,
    JSelectEmployeeModal,
  },
  data() {
    return {
      description: '领料单管理',
      // 用于强制刷新日期选择器
      datePickerKey: 0,
      // 查询条件
      queryParam: {
        requisitionDate: null, // 初始化领料日期为null
        approveTime: null, // 初始化审核日期为null
        approver: '', // 初始化审核人为空字符串
        requisitionNo_like: '', // 领料单号，模糊查询
        orderNo_like: '', // 订单编号，模糊查询
        status: '', // 审核状态
        pickingStatus: '', // 领料状态
        beginRequisitionDate: null, // 领料开始日期
        endRequisitionDate: null, // 领料结束日期
        beginApproveDate: null, // 审核开始日期
        endApproveDate: null, // 审核结束日期
        approverName: '', // 审核人名称
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '领料单号',
          align: 'center',
          dataIndex: 'requisitionNo',
        },
        {
          title: '订单编号',
          align: 'center',
          dataIndex: 'orderNo',
        },
        {
          title: '优化类型',
          align: 'center',
          dataIndex: 'optimizationSoftwareType',
          scopedSlots: { customRender: 'optimizationSoftwareTypeSlot' },
        },
        {
          title: '审核时间',
          align: 'center',
          dataIndex: 'approveTime',
        },
        {
          title: '审核人',
          align: 'center',
          dataIndex: 'approverName',
        },
        {
          title: '审核状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '领料日期',
          align: 'center',
          dataIndex: 'requisitionDate',
        },
        {
          title: '领料人',
          align: 'center',
          dataIndex: 'requisitionPerson',
        },
        {
          title: '领料状态',
          align: 'center',
          dataIndex: 'pickingStatus',
          scopedSlots: { customRender: 'pickingStatusSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/requisition/list',
        delete: '/wms/requisition/delete',
        deleteBatch: '/wms/requisition/deleteBatch',
        exportXlsUrl: '/wms/requisition/exportXls',
        approve: '/wms/requisition/approve',
        reject: '/wms/requisition/reject',
        execute: '/wms/requisition/execute',
        print: '/wms/requisition/print',
      },
      // 权限相关
      permissionList: [],
      // 控制查询条件展开收起
      toggleSearchStatus: false,
    }
  },
  created() {
    // 加载字典数据
    this.initDictConfig()

    // 加载权限列表
    this.loadPermissions()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  methods: {
    // 加载权限
    loadPermissions() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 添加领料单
    handleAdd() {
      try {
        console.log('开始打开新增领料单弹窗')
        this.$refs.modalForm.add()
        console.log('新增领料单弹窗打开成功')
      } catch (error) {
        console.error('打开新增领料单弹窗失败:', error)
      }
    },

    // 查看领料单详情
    handleView(record) {
      this.$refs.viewModal.show(record.id)
    },

    // 审核
    handleApprove(record) {
      this.$refs.approveModal.show(record)
    },

    // 驳回
    handleReject(record) {
      this.$refs.rejectModal.show(record)
    },

    // 打印
    handlePrint(record) {
      this.$refs.printModal.show(record.id)
    },

    // 导出Excel
    handleExport() {
      if (!this.url.exportXlsUrl) {
        this.$message.error('请设置url.exportXlsUrl属性!')
        return
      }

      // 构建查询参数，不包括日期数组
      let params = this.getQueryParams()

      // 移除可能导致后端类型转换错误的日期数组
      if (params.requisitionDate) {
        delete params.requisitionDate
      }
      if (params.approveTime) {
        delete params.approveTime
      }

      console.log('导出参数:', params)

      // 使用downFile函数导出Excel
      this.loading = true
      downFile(this.url.exportXlsUrl, params).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), '领料单.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '领料单.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
        this.loading = false
      })
    },

    // // 批量打印领料单
    // handleBatchPrint() {
    //   if (this.selectedRowKeys.length === 0) {
    //     this.$message.warning('请至少选择一条领料单');
    //     return;
    //   }
    //   this.$refs.printModal.batchPrint(this.selectedRowKeys);
    // },

    // 审核信息
    handleViewApproveInfo(record) {
      this.$refs.approveInfoModal.show(record.id)
    },

    // 切换查询条件的展开/收起状态
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },

    // 处理领料日期变更
    handleRequisitionDateChange(dates, dateStrings) {
      console.log('领料日期变更:', dates, dateStrings)
      if (dates && dates.length === 2) {
        // 将日期字符串保存到查询参数
        this.queryParam.beginRequisitionDate = dateStrings[0]
        this.queryParam.endRequisitionDate = dateStrings[1]
        // 保存moment对象数组，用于日期选择器显示
        this.queryParam.requisitionDate = dates
      } else {
        // 清空日期相关参数
        this.queryParam.beginRequisitionDate = null
        this.queryParam.endRequisitionDate = null
        this.queryParam.requisitionDate = null
      }
      console.log('领料日期变更后的查询参数:', JSON.stringify(this.queryParam))
    },

    // 处理审核日期变更
    handleApproveTimeChange(dates, dateStrings) {
      console.log('审核日期变更:', dates, dateStrings)
      if (dates && dates.length === 2) {
        // 将日期字符串保存到查询参数
        this.queryParam.beginApproveDate = dateStrings[0]
        this.queryParam.endApproveDate = dateStrings[1]
        // 保存moment对象数组，用于日期选择器显示
        this.queryParam.approveTime = dates
      } else {
        // 清空日期相关参数
        this.queryParam.beginApproveDate = null
        this.queryParam.endApproveDate = null
        this.queryParam.approveTime = null
      }
      console.log('审核日期变更后的查询参数:', JSON.stringify(this.queryParam))
    },

    // 重写searchQuery方法，处理日期范围参数
    searchQuery() {
      // 不需要清除日期数组，因为我们现在使用它来回显日期选择器的值
      console.log('执行查询，参数:', this.queryParam)
      this.loadData(1)
      this.$nextTick(() => {
        this.onClearSelected()
      })
    },

    // 重写searchReset方法，清空日期范围
    searchReset() {
      // 清空所有查询条件
      this.queryParam = {
        requisitionDate: null,
        approveTime: null,
        approver: '',
        requisitionNo_like: '',
        orderNo_like: '',
        status: '',
        pickingStatus: '',
        beginRequisitionDate: null,
        endRequisitionDate: null,
        beginApproveDate: null,
        endApproveDate: null,
        approverName: '',
      }

      // 增加datePickerKey，强制刷新日期选择器
      this.datePickerKey += 1

      console.log('重置查询条件:', this.queryParam, '日期选择器Key:', this.datePickerKey)
      this.loadData(1)
      this.$nextTick(() => {
        this.onClearSelected()
      })
    },

    // 处理审核人选择的改变
    handleApproverChange(value, selectedEmployees) {
      // 当选择了审核人后，value是审核人的username，selectedEmployees包含完整的员工信息
      if (selectedEmployees && selectedEmployees.length > 0) {
        // 设置审核人名称，用于显示
        this.queryParam.approverName = selectedEmployees[0].empName
      } else {
        this.queryParam.approverName = ''
      }
    },

    // 获取日历容器，防止日期选择器被遮挡
    getCalendarContainer() {
      return document.body
    },

    // 重写JeecgListMixin中的loadData方法
    loadData(arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }

      // 构建查询参数，不包括日期数组
      var params = this.getQueryParams()

      // 移除可能导致后端类型转换错误的日期数组
      if (params.requisitionDate) {
        delete params.requisitionDate
      }
      if (params.approveTime) {
        delete params.approveTime
      }

      console.log('发送查询参数:', params)

      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.ipagination.total = res.result.total || 0
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style lang="less" scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}
.ant-table-tbody .ant-table-row td {
  padding-top: 8px;
  padding-bottom: 8px;
}
.anty-row-operator button {
  margin: 0 5px;
}
.ant-btn-danger {
  background-color: #ffffff;
}
.ant-modal-cust-warp {
  height: 100%;
}
.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}
.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}
.table-wrapper {
  position: relative;
  height: calc(100vh - 280px);
  overflow: hidden;
}
.requisition-table {
  margin-top: 10px;
}
.requisition-table .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  overflow: hidden;
  height: auto;
}
.requisition-table .ant-table-body {
  overflow-x: auto !important;
}
.requisition-table .ant-table-thead > tr > th {
  background-color: #f5f5f5;
  font-weight: bold;
}
.requisition-table .ant-table-tbody > tr:hover > td {
  background-color: #e6f7ff;
}
</style> 